package ch.bfh.abcmmh.view.detailview.gcarfactory;

import java.awt.Color;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;
import java.util.Random;

import ch.bfh.abcmmh.controller.operating.clock.Clock;
import ch.bfh.abcmmh.model.cars.Vehicle;
import ch.bfh.abcmmh.model.cars.specialVehicles.Bus;
import ch.bfh.abcmmh.model.cars.specialVehicles.Car;
import ch.bfh.abcmmh.model.cars.specialVehicles.Truck;
import ch.bfh.abcmmh.view.detailview.Cars.GBus;
import ch.bfh.abcmmh.view.detailview.Cars.GCar;
import ch.bfh.abcmmh.view.detailview.Cars.GTruck;
import ch.bfh.abcmmh.view.detailview.Cars.GVehicle;
import ch.bfh.abcmmh.view.detailview.streets.StreetPanel;

public class GCarFactory implements Observer {

	private StreetPanel streetPanel;
	private Clock clock;

	private ArrayList<Vehicle> gCars;

	public GCarFactory(Clock clock, StreetPanel streetPanel) {

		this.streetPanel = streetPanel;

		this.clock = clock;

	}

	public void update(Observable o, Object arg) {

		if (Vehicle.class.isInstance(arg)) {
			putNewVehicleOnStreet((Vehicle) arg);

		} else {
			throw new RuntimeException();
		}

	}

	public void paintGCarList() {
		for (int i = 0; i < gCars.size(); i++) {
			putNewVehicleOnStreet(gCars.get(i));
		}
	}

	private void putNewVehicleOnStreet(Vehicle v) {
		if (Car.class.isInstance(v)) {
			Car car = (Car) v;
			GCar gCar = new GCar(car, this.randomColor(), streetPanel);
			paintVehicleonStreet(gCar);
		}
		if (Bus.class.isInstance(v)) {
			Bus bus = (Bus) v;
			GBus gBus = new GBus(bus, this.randomColor(), streetPanel);
			paintVehicleonStreet(gBus);
		}
		if (Truck.class.isInstance(v)) {
			Truck truck = (Truck) v;
			GTruck gTruck = new GTruck(truck, this.randomColor(), streetPanel);
			paintVehicleonStreet(gTruck);
		}
	}

	private void paintVehicleonStreet(GVehicle gVehicle) {
		clock.addObserver(gVehicle);
		streetPanel.getStreetController().addObserver(gVehicle);
		int streetnumber = gVehicle.getVehicle().getStreetNumber();
		gVehicle.setLocation(gVehicle.getVehicle().getPosition()
				- streetPanel.getStreetController().getCurrentPos() -50,  //<--workaraound
				streetPanel.getStreetMidley(streetnumber));
		streetPanel.add(gVehicle);
		streetPanel.repaintSubsandMe();
	}

	public int getStreetHigh(int streetnumber) {
		return 3;
	}

	private Color randomColor() {
		Random rand = new Random();
		float r =(float) 0.3333333; //rand.nextFloat();
		float g =(float) 0.55555555; rand.nextFloat();
		float b = rand.nextFloat();
	
		return new Color(r, g, b);
		
	}

	public StreetPanel getStreetPanel() {
		return streetPanel;
	}

}
